package cn.tedu.ivos.dict.Service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.dict.Service.DictService;
import cn.tedu.ivos.dict.mapper.DictMapper;
import cn.tedu.ivos.dict.pojo.dto.DictAddParam;
import cn.tedu.ivos.dict.pojo.dto.DictQuery;
import cn.tedu.ivos.dict.pojo.entity.Dict;
import cn.tedu.ivos.dict.pojo.vo.DictVO;
import cn.tedu.ivos.dictoption.mapper.DictOptionMapper;
import cn.tedu.ivos.dictoption.pojo.dto.DictOptionQuery;
import cn.tedu.ivos.dictoption.pojo.vo.DictOptionVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class DictServiceImpl implements DictService {
    @Autowired
    DictMapper dictMapper;
    @Autowired
    DictOptionMapper dictOptionMapper;

    @Override
    public List<DictVO> selectDict(DictQuery query) {
        log.debug("查询字典业务，参数：{}", query);
        return dictMapper.selectDict(query);

    }

    @Override
    public void saveDict(DictAddParam dictAddParam) {
        log.debug("保存字典业务，参数：{}", dictAddParam);
        Dict dict = new Dict();
        if (dictAddParam.getId() == null ) {
            BeanUtils.copyProperties(dictAddParam, dict);
            dict.setCreateTime(new Date());
            dictMapper.insertDict(dict);
        }else {
            BeanUtils.copyProperties(dictAddParam, dict);
            dict.setUpdateTime(new Date());
            dictMapper.updateDict(dict);
        }


    }

    @Override
    public void deleteDict(Long id) {
        log.debug("删除字典业务，id:{}", id);
        DictOptionQuery query = new DictOptionQuery();
        query.setDictId(id);
        List<DictOptionVO> list = dictOptionMapper.selectDictOption(query);
        if (!list.isEmpty()){
            throw new ServiceException(StatusCode.DICTOPTION_EXISTS);
        }else {
            dictMapper.deleteDict(id);
        }
    }
}
